/**
 * 对数据进行签名
 * @author adv30 <adv30@126.com>
 * 2017年5月26日10:40:07
 */
const qs = require('qs')
const Base = require('../base/Base')
const md5 = require('blueimp-md5')
const isFunction = require('lodash/isFunction')
class ApiKey extends Base
{
    // 包装获取签名
    wrapper (pathObj, data, type = 'string') {
        let send = {}
        send.sendTime = (Date.parse(new Date()) + '').substring(0, 10)
        send.ver = pathObj.ver
        send.module = pathObj.module
        send.controller = pathObj.controller
        send.action = pathObj.action
        send.encryption = 'off'
        send.expiry = 0
        send.textData = JSON.stringify(data) 
        // 签名
        let functionName = '_' + send.ver + 'Sign'
        if (isFunction(this[functionName])) {
            this[functionName]
        } else {
            this._defaultSign(send)
        }
        return type === 'string' ? qs.stringify(send) : send
    }
    // 默认的签名方法
    _defaultSign (send) {
        let keyA = send.sendTime.substring(0, 5)
        let keyB = send.sendTime.substring(5, 10)
        send.appkey = md5(send.ver + keyA + send.encryption + send.module + keyB + send.controller + send.action)
    }
}

module.exports = new ApiKey()